<template>
  <div class="system-container">
    <el-tabs v-model="activeTab">
      <!-- 基本设置 -->
      <el-tab-pane label="基本设置" name="basic">
        <el-form
          ref="basicFormRef"
          :model="basicForm"
          :rules="basicRules"
          label-width="120px"
        >
          <el-form-item label="系统名称" prop="systemName">
            <el-input v-model="basicForm.systemName" />
          </el-form-item>
          <el-form-item label="系统Logo">
            <el-upload
              class="logo-uploader"
              action="/api/upload"
              :show-file-list="false"
              :on-success="handleLogoSuccess"
            >
              <img v-if="basicForm.logo" :src="basicForm.logo" class="logo">
              <el-icon v-else class="logo-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
          <el-form-item label="联系人" prop="contact">
            <el-input v-model="basicForm.contact" />
          </el-form-item>
          <el-form-item label="联系电话" prop="phone">
            <el-input v-model="basicForm.phone" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="saveBasicSettings">保存设置</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>

      <!-- 告警设置 -->
      <el-tab-pane label="告警设置" name="alarm">
        <el-form
          ref="alarmFormRef"
          :model="alarmForm"
          :rules="alarmRules"
          label-width="120px"
        >
          <el-form-item label="启用告警">
            <el-switch v-model="alarmForm.enabled" />
          </el-form-item>
          <el-form-item label="告警阈值" prop="threshold">
            <el-input-number v-model="alarmForm.threshold" :min="0" :max="1000" />
            <span class="unit">kWh</span>
          </el-form-item>
          <el-form-item label="告警方式">
            <el-checkbox-group v-model="alarmForm.methods">
              <el-checkbox label="email">邮件</el-checkbox>
              <el-checkbox label="sms">短信</el-checkbox>
              <el-checkbox label="weixin">微信</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="告警时间">
            <el-time-picker
              v-model="alarmForm.startTime"
              format="HH:mm"
              placeholder="开始时间"
            />
            <span class="separator">-</span>
            <el-time-picker
              v-model="alarmForm.endTime"
              format="HH:mm"
              placeholder="结束时间"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="saveAlarmSettings">保存设置</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>

      <!-- 用户管理 -->
      <el-tab-pane label="用户管理" name="user">
        <div class="table-operations">
          <el-button type="primary" @click="handleAddUser">
            <el-icon><Plus /></el-icon>新增用户
          </el-button>
        </div>
        
        <el-table :data="userList" border style="width: 100%">
          <el-table-column prop="username" label="用户名" />
          <el-table-column prop="realName" label="姓名" />
          <el-table-column prop="role" label="角色" />
          <el-table-column prop="phone" label="手机号" />
          <el-table-column prop="email" label="邮箱" />
          <el-table-column prop="status" label="状态">
            <template #default="{ row }">
              <el-tag :type="row.status === 1 ? 'success' : 'danger'">
                {{ row.status === 1 ? '启用' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200">
            <template #default="{ row }">
              <el-button link type="primary" @click="handleEditUser(row)">编辑</el-button>
              <el-button link type="primary" @click="handleResetPassword(row)">重置密码</el-button>
              <el-button 
                link 
                :type="row.status === 1 ? 'danger' : 'success'"
                @click="handleToggleStatus(row)"
              >
                {{ row.status === 1 ? '禁用' : '启用' }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>

    <!-- 用户编辑对话框 -->
    <el-dialog
      v-model="userDialogVisible"
      :title="userDialogType === 'add' ? '新增用户' : '编辑用户'"
      width="500px"
    >
      <el-form
        ref="userFormRef"
        :model="userForm"
        :rules="userRules"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" :disabled="userDialogType === 'edit'" />
        </el-form-item>
        <el-form-item label="姓名" prop="realName">
          <el-input v-model="userForm.realName" />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="userForm.role">
            <el-option label="管理员" value="admin" />
            <el-option label="操作员" value="operator" />
            <el-option label="查看者" value="viewer" />
          </el-select>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="userForm.phone" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="userDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSaveUser">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance } from 'element-plus'

// 当前激活的标签页
const activeTab = ref('basic')

// 基本设置
const basicFormRef = ref<FormInstance>()
const basicForm = reactive({
  systemName: '能耗托线监测系统',
  logo: '',
  contact: '',
  phone: ''
})

const basicRules = {
  systemName: [{ required: true, message: '请输入系统名称', trigger: 'blur' }],
  contact: [{ required: true, message: '请输入联系人', trigger: 'blur' }],
  phone: [{ required: true, message: '请输入联系电话', trigger: 'blur' }]
}

// 告警设置
const alarmFormRef = ref<FormInstance>()
const alarmForm = reactive({
  enabled: true,
  threshold: 100,
  methods: ['email'],
  startTime: new Date(2000, 1, 1, 0, 0),
  endTime: new Date(2000, 1, 1, 23, 59)
})

const alarmRules = {
  threshold: [{ required: true, message: '请输入告警阈值', trigger: 'blur' }]
}

// 用户管理
const userList = ref([
  {
    username: 'admin',
    realName: '管理员',
    role: '管理员',
    phone: '13800138000',
    email: 'admin@example.com',
    status: 1
  }
])

const userDialogVisible = ref(false)
const userDialogType = ref<'add' | 'edit'>('add')
const userFormRef = ref<FormInstance>()
const userForm = reactive({
  username: '',
  realName: '',
  role: '',
  phone: '',
  email: ''
})

const userRules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  realName: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  role: [{ required: true, message: '请选择角色', trigger: 'change' }]
}

// 保存基本设置
const saveBasicSettings = async () => {
  if (!basicFormRef.value) return
  await basicFormRef.value.validate((valid) => {
    if (valid) {
      // TODO: 实现保存逻辑
      ElMessage.success('保存成功')
    }
  })
}

// 保存告警设置
const saveAlarmSettings = async () => {
  if (!alarmFormRef.value) return
  await alarmFormRef.value.validate((valid) => {
    if (valid) {
      // TODO: 实现保存逻辑
      ElMessage.success('保存成功')
    }
  })
}

// Logo上传成功回调
const handleLogoSuccess = (response: any) => {
  basicForm.logo = response.url
}

// 用户相关操作
const handleAddUser = () => {
  userDialogType.value = 'add'
  userDialogVisible.value = true
  userForm.username = ''
  userForm.realName = ''
  userForm.role = ''
  userForm.phone = ''
  userForm.email = ''
}

const handleEditUser = (row: any) => {
  userDialogType.value = 'edit'
  userDialogVisible.value = true
  Object.assign(userForm, row)
}

const handleResetPassword = (row: any) => {
  ElMessageBox.confirm(`确认重置用户"${row.username}"的密码吗？`, '提示', {
    type: 'warning'
  }).then(() => {
    // TODO: 实现重置密码逻辑
    ElMessage.success('密码重置成功')
  })
}

const handleToggleStatus = (row: any) => {
  const action = row.status === 1 ? '禁用' : '启用'
  ElMessageBox.confirm(`确认${action}用户"${row.username}"吗？`, '提示', {
    type: 'warning'
  }).then(() => {
    // TODO: 实现状态切换逻辑
    row.status = row.status === 1 ? 0 : 1
    ElMessage.success(`${action}成功`)
  })
}

const handleSaveUser = async () => {
  if (!userFormRef.value) return
  await userFormRef.value.validate((valid) => {
    if (valid) {
      // TODO: 实现保存逻辑
      userDialogVisible.value = false
      ElMessage.success(userDialogType.value === 'add' ? '新增成功' : '编辑成功')
    }
  })
}
</script>

<style lang="scss" scoped>
.system-container {
  padding: 20px;
  
  .logo-uploader {
    border: 1px dashed $border-color;
    border-radius: $border-radius-base;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 120px;
    height: 120px;
    
    .logo {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
    
    .logo-uploader-icon {
      font-size: 28px;
      color: $text-color-secondary;
      width: 100%;
      height: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
  
  .unit {
    margin-left: 10px;
    color: $text-color-secondary;
  }
  
  .separator {
    margin: 0 10px;
    color: $text-color-secondary;
  }
  
  .table-operations {
    margin-bottom: 20px;
  }
}
</style>
